package com.fy.oa.zc.menu.manager;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.ResultSetExtractor;
import org.springframework.jdbc.core.RowMapper;

public final class FyReportMenuAccessManagerImpl implements FyReportMenuAccessManager {
	private JdbcTemplate jdbcTemplate;
	private static Map<String, Object> menuAccessMap;
	/**
	 * 管理员ＩＤ
	 */
	private String managerID;

	@Override
	public void setManagerID(String managerID) {
		this.managerID = managerID;
	}

	public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
		this.jdbcTemplate = jdbcTemplate;
	}

	public void saveAccess(String menuType, List<String> members) {
		menuAccessMap = null;
	}

	public boolean haveAccess(String memberID, String menuType) {
		if (this.managerID != null && this.managerID.equals(memberID)) {
			menuAccessMap = null;
			return true;
		} else {
			try {
				if (menuAccessMap == null) {
					synchronized (FyReportMenuAccessManagerImpl.class) {
						if (menuAccessMap == null) {

							menuAccessMap = jdbcTemplate.query(
									"select memberid,wmsys.wm_concat(menutype) from fy_report_menu_access group by memberid",
									new ResultSetExtractor<Map<String, Object>>() {
										@Override
										public Map<String, Object> extractData(ResultSet rs)
												throws SQLException, DataAccessException {
											Map<String, Object> map = new HashMap<String, Object>();
											while (rs.next()) {
												map.put(rs.getString(1), rs.getString(2));
											}
											return map;
										}
									});
						}
					}
				}
//				System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>");
//				System.out.println(memberID);
//				System.out.println(menuAccessMap.get(memberID));
//				System.out.println(menuType);
				String access = String.valueOf(menuAccessMap.get(memberID));
//				System.out.println("<<<<<<<<<<<<<<<<<<<<<<<<<<<");
				return access != null && access.contains(menuType);
			} catch (Exception e) {
				return false;
			}
		}
	}
}
